/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.foundation.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by cherry on 2016/8/12.
 */
public class SamplePdfBuilder implements PdfBuilder {

    private Document document;

    public SamplePdfBuilder() {
        document = new Document();
    }

    @Override
    public void drawPdf(String filePath, ExPdfPageFactory factory) {

        List<ExPdfPage> pdfPages = factory.getPdfPages();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(filePath));
            document.open();
            if (pdfPages != null && !pdfPages.isEmpty()) {
                for (int i = 0; i < pdfPages.size(); i++) {
                    fillDataToPdf(pdfPages.get(i));
                }
            }
        } catch (DocumentException e) {

            e.printStackTrace();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } finally {

            document.close();
        }
    }

    private void fillDataToPdf(ExPdfPage exPdfPage) {
        Paragraph title = exPdfPage.getPageTitle();
        List<PdfPTable> tables = exPdfPage.getTables();
        try {
            document.newPage();
            document.add(title);
            if (tables != null && !tables.isEmpty()) {
                for (int i = 0; i < tables.size(); i++) {
                    document.add(tables.get(i));
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
